package com.javaclimb.music.controller;

import com.javaclimb.music.domain.Singer;
import com.javaclimb.music.domain.SongList;
import com.javaclimb.music.enums.ResponseEnum;
import com.javaclimb.music.service.SongListService;
import com.javaclimb.music.vo.ResponseVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.List;

import static com.javaclimb.music.enums.ResponseEnum.ERROR_UPLOAD;

/**
 * @author 最酷的桃儿wjc
 * * @date 2022/5/21
 */
@RestController
@RequestMapping("/song")
public class SongListController {
    /**
     * 获取歌单列表
     */
    @Autowired
    private SongListService songListService;
    @GetMapping("/songList")
    public List<SongList> getSongLists(){
        return songListService.getAllLists();
    }

    /**
     * 添加歌单
     * @param songList
     * @return
     */
    @PostMapping("/addSongList")
    public ResponseVo insertSongList(SongList songList){
        return songListService.addSongList(songList);
    }


    @PostMapping("/updatePic")
    public ResponseVo updateSongListPic(@RequestParam("file")MultipartFile multipartFile ,@RequestParam("id")Integer id){
//        后台用partfile接收前台封装好的file
        if(multipartFile.isEmpty()){
            return ResponseVo.error(ERROR_UPLOAD);
        }
//        获取原文件名 = 当前秒数+上传文件名
        String filename = System.currentTimeMillis() + multipartFile.getOriginalFilename();
//存储的文件路径
        String filePath = System.getProperty("user.dir")+System.getProperty("file.separator")+"img"+System.getProperty("file.separator")+"songListPic";
        File file = new File(filePath);
//        判断文件路径是否存在如果不存在就要新建
        if (!file.exists()){
            file.mkdirs();
        }
//        实际的文件地址
        File dest = new File(filePath+System.getProperty("file.separator")+filename);
//       存储到数据库里的相对文件地址
        String storeAvatorPath = "/img/songListPic/"+ filename;
        try {
            multipartFile.transferTo(dest);
            SongList songList = new SongList();
            songList.setId(id);
            songList.setPic(storeAvatorPath);
            return songListService.updateSongListPic(songList,storeAvatorPath);
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseVo.error(ERROR_UPLOAD);
        }
    }

}
